<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use app\api\model\Blacklist;
use think\Db;
use think\Request;

class Dating extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    /**
     * @return mixed
     */
    public function lists() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $sex       = $this->member['sex'] == '男' ? '女' : '男';
        $agemin    = $this->params['agemin'] ?? 0;
        $agemax    = $this->params['agemax'] ?? 0;
        $heightmin = $this->params['heightmin'] ?? 0;
        $heightmax = $this->params['heightmax'] ?? 0;
        $province  = $this->params['province'] ?? '';
        $city      = $this->params['city'] ?? '';
        $education = $this->params['education'] ?? '';
        $enter = $this->params['enter'] ?? 0;

        $where = [
            'd.state'         => 1,
            'd.expire_time'   => ['>', time()],
            'u.delete_time'   => 0,
            'u.is_banned'     => 0,
            'u.entertainment' => 3,
            'u.sex'           => $sex,
        ];

        if ($agemax) {
            if ($agemin) {
                $where['u.age'] = ['between', [$agemin, $agemax]];
            } else {
                $where['u.age'] = ['<=', $agemax];
            }
        } elseif ($agemin) {
            $where['u.age'] = ['>=', $agemin];
        }

        if ($heightmax) {
            if ($heightmin) {
                $where['u.stature'] = ['between', [$heightmin, $heightmax]];
            } else {
                $where['u.stature'] = ['<=', $heightmax];
            }
        } elseif ($heightmin) {
            $where['u.stature'] = ['>=', $heightmin];
        }

        if ($province) {
            $where['u.province'] = $province;
        }
        if ($city) {
            $where['u.city'] = $city;
        }
        if ($education) {
            $edus         = ['初中' => 1, '中专' => 2, '高中' => 3, '大专' => 4, '本科' => 5, '双学士' => 6, '硕士' => 7, '博士' => 8];
            $datingEduIdx = 0;
            $edusWhere    = [];
            foreach ($edus as $key => $value) {
                if ($datingEduIdx) {
                    if ($value >= $datingEduIdx) {
                        $edusWhere[] = $key;
                    }
                    continue;
                }
                if (strpos($education, $key) !== false) {
                    $datingEduIdx = $value;
                    $edusWhere[]  = $key;
                }
            }
            $where['u.education_background'] = ['in', $edusWhere];
        }

        $blacklist = Blacklist::lists($this->member['id'], false, false);
        if ($blacklist) {
            $where['d.user_id'] = ['not in', $blacklist];
        }

        if ($enter) {
            $enter = Db::name('dating')
                ->alias('d')
                ->join('user u', 'd.user_id=u.id')
                ->where($where)
                ->limit(1)
                ->count();
            return $this->pass(['enter'=>$enter>=1]);
        }
        // return $this->pass($where);
        $data = Db::name('dating')
            ->alias('d')
            ->join('user u', 'd.user_id=u.id')
            ->where($where)
            ->page($page)
            ->limit($pagesize)
            ->field('d.id,d.user_id,d.title,d.content,d.agemin,d.agemax,d.heightmin,d.heightmax,d.province,d.city,d.education,d.images,d.create_time,d.expire_time, u.name,u.head_portrait, u.sex, u.age, u.remote')
            // ->order('create_time desc')
            ->orderRaw('CASE WHEN d.user_id > 20000000 OR d.user_id < 10000000 THEN 1 ELSE 2 END, d.user_id desc')
            ->select();

        $intos     = Db::name('dating_into')->master()->where(['user_id' => $this->member['id']])->column('dating_id');
        $into_list = Db::name('dating_into')
            ->alias('d')
            ->join('user u', 'd.user_id=u.id')
            ->where(['dating_id' => ['in', array_column($data, 'id')]])
            ->field('head_portrait,dating_id')
            ->select();
        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d', $value['create_time']);
            $value['expire_time'] = date('Y-m-d', $value['expire_time']);

            if ($value['images']) {
                $value['images'] = explode(',', $value['images']);
            } else {
                $value['images'] = [];
            }
            if ($value['remote'] == 10) {
                foreach ($value['images'] as &$imgv) {
                    $imgv = changeUrl($imgv, 0);
                }
                $value['head_portrait'] = changeUrl($value['head_portrait'], 0);
            }
            unset($value['remote']);

            $value['is_into']   = in_array($value['id'], $intos);
            $value['into_list'] = [];
            foreach ($into_list as $k => $v) {
                if ($v['dating_id'] == $value['id']) {
                    $value['into_list'][] = $v['head_portrait'];
                }
            }
        }

        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function mylists() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $where = [
            'user_id' => $this->member['id'],
        ];

        $data = Db::name('dating')
            ->where($where)
            ->page($page)
            ->limit($pagesize)
            ->order('id desc')
            ->select();

        $into_list = Db::name('dating_into')
            ->alias('d')
            ->join('user u', 'd.user_id=u.id')
            ->where(['dating_id' => ['in', array_column($data, 'id')]])
            ->field('head_portrait,name,user_id,dating_id')
            ->select();
        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d', $value['create_time']);
            $value['expire_time'] = date('Y-m-d', $value['expire_time']);
            $value['audit_time'] = date('Y-m-d', $value['audit_time']);

            if ($value['images']) {
                $value['images'] = explode(',', $value['images']);
            } else {
                $value['images'] = [];
            }

            $value['into_list'] = [];
            foreach ($into_list as $k => $v) {
                if ($v['dating_id'] == $value['id']) {
                    $value['into_list'][] = $v;
                }
            }
        }

        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function into() {
        $did     = $this->params['did'] ?? '';
        $content = $this->params['content'] ?? '';

        if ($this->member['sex'] == '女' && $this->member['entertainment'] != 2) {
            return $this->miss('您的使用目的并非交友,暂不支持应征');
        }

        $datingInfo = Db::name('dating')->find($did);

        if (!$datingInfo) {
            return $this->miss('操作失败');
        }

        if ($datingInfo['state'] != 1) {
            return $this->miss('操作失败');
        }

        if ($datingInfo['expire_time'] < time()) {
            return $this->miss('已截止');
        }

        if (!$content) {
            return $this->miss('请输入应征留言');
        }

        $isInto = Db::name('dating_into')->master()->where(['user_id' => $this->member['id'], 'dating_id' => $did])->find();
        if ($isInto) {
            return $this->miss('您已应征此征婚');
        }

        if ($datingInfo['agemin']) {
            if (!$this->member['age']) {
                return $this->miss('请先设置年龄');
            }

            if ($this->member['age'] < $datingInfo['agemin']) {
                return $this->miss('您的年龄不符合对方征婚要求');
            }

        }
        if ($datingInfo['agemax']) {
            if (!$this->member['age']) {
                return $this->miss('请先设置年龄');
            }

            if ($this->member['age'] > $datingInfo['agemax']) {
                return $this->miss('您的年龄不符合对方征婚要求');
            }

        }
        if ($datingInfo['heightmin']) {
            if (!$this->member['stature']) {
                return $this->miss('请先设置身高');
            }

            if ($this->member['stature'] < $datingInfo['heightmin']) {
                return $this->miss('您的身高不符合对方征婚要求');
            }

        }
        if ($datingInfo['heightmax']) {
            if (!$this->member['stature']) {
                return $this->miss('请先设置身高');
            }

            if ($this->member['stature'] > $datingInfo['heightmax']) {
                return $this->miss('您的身高不符合对方征婚要求');
            }

        }
        if ($datingInfo['province']) {
            if (!$this->member['province']) {
                return $this->miss('未获取到你所在的地区');
            }

            if ($datingInfo['province'] != $this->member['province']) {
                return $this->miss('您的地区不符合对方征婚要求');
            }

        }
        if ($datingInfo['city']) {
            if (!$this->member['city']) {
                return $this->miss('未获取到你所在的地区');
            }

            if ($datingInfo['city'] != $this->member['city']) {
                return $this->miss('您的地区不符合对方征婚要求');
            }

        }
        if ($datingInfo['education']) {
            if (!$this->member['education_background']) {
                return $this->miss('请先设置学历');
            }

            $edus         = ['初中' => 1, '中专' => 2, '高中' => 3, '大专' => 4, '本科' => 5, '双学士' => 6, '硕士' => 7, '博士' => 8];
            $myeduIdx     = $edus[$this->member['education_background']];
            $datingEduIdx = 0;
            foreach ($edus as $key => $value) {
                if (strpos($datingInfo['education'], $key) !== false) {
                    $datingEduIdx = $value;
                    break;
                }
            }
            if ($myeduIdx < $datingEduIdx) {
                return $this->miss('您的学历不符合对方征婚要求');
            }

        }

        if (mb_strlen($content) > 100) return $this->miss('内容限制长度100');
        if(is_hasNumber($content) || is_hasCnNumber($content)) return $this->miss('当前禁止发送数字');

        // 敏感词检测
        $contain = Db::name('filter_word')->cache(true, 3600)->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) {
                return $this->miss('消息含有敏感词"' . $v . '",请重新编辑发送');
            }
        }
        $contain = Db::name('ban_word')->where(['state' => 1])->column('name');
        $maskArr = ['', '*', '**', '***', '****', '*****'];
        $sysMask = false;
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) {
                $content = str_replace($v, $maskArr[mb_strlen($v)] ?? '*', $content);
            }
        }

        $res = Db::name('dating_into')->insertGetId([
            'dating_id' => $did,
            'user_id'   => $this->member['id'],
            'touser_id' => $datingInfo['user_id'],
            'content'   => $content,
            'time'      => time(),
        ]);

        if ($res) {
            $datas = [
                'userid'   => $this->member['id'],
                'touserid' => $datingInfo['user_id'],
                'type'     => 20,
                'content'  => $content,
                'data'     => json_encode(['did' => $did, 'dm_id'=>$res], JSON_UNESCAPED_UNICODE),
            ];

            $request = request();
            $url     = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';
            curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));

            $touserinfo = Db::name('user')->find($datingInfo['user_id']);
            $todaysend = Db::name('chat_lists_smstip')->where(['another_id'=>$touserinfo['id']])->whereTime('time','-168 hours')->cache(60)->find();
            if (!$todaysend) {
                $url = 'http://utf8.api.smschinese.cn/';
                $content = "你发布的信息已经有人应征，请登录那蓝之恋app查看";

                $data = "?Uid=" . getenv('WEBSMS_UID') . "&Key=" . getenv('WEBSMS_KEY') . "&smsMob=" . $touserinfo['phone'] . "&smsText=" . $content;

                $result = file_get_contents($url . $data);

                if ($result != 1) {
                } else {
                    Db::name('chat_lists_smstip')->insert([
                        'user_id'   => $this->member['id'],
                        'another_id'=> $touserinfo['id'],
                        'time'      => time()
                    ]);
                }
            }

            return $this->pass('应征成功,等待对方回应');
        }
        return $this->miss('请重试');
    }

    /**
     * @return mixed
     */
    public function publish() {
        if ($this->member['sex'] == '女' && $this->member['entertainment'] != 2) {
            return $this->miss('您的使用目的并非交友,暂不支持发布征婚信息');
        }

        $title      = $this->params['title'] ?? '';
        $agemin     = $this->params['agemin'] ?? 0;
        $agemax     = $this->params['agemax'] ?? 0;
        $heightmin  = $this->params['heightmin'] ?? 0;
        $heightmax  = $this->params['heightmax'] ?? 0;
        $province   = $this->params['province'] ?? '';
        $city       = $this->params['city'] ?? '';
        $education  = $this->params['education'] ?? '';
        $content    = $this->params['content'] ?? '';
        $title=iconv("utf-8","gbk//IGNORE",$title);
        $title = mb_convert_encoding($title,'UTF-8','GBK');
        $content=iconv("utf-8","gbk//IGNORE",$content);
        $content = mb_convert_encoding($content,'UTF-8','GBK');
        
        // $images     = $this->params['images'] ?? '';
        $images     = input('images', '');
        $expire_day = $this->params['expire_day'] ?? 0;
        $test       = $this->params['test'] ?? 0;

        if (!$title) {
            return $this->miss('标题不能为空');
        }

        if (!$agemin) {
            return $this->miss('请选择年龄');
        }

        if ($agemin > $agemax) {
            return $this->miss('年龄选择错误');
        }

        if ($heightmin > $heightmax) {
            return $this->miss('身高选择错误');
        }

        if (!$expire_day || $expire_day < 0) {
            return $this->miss('请选择有效时间');
        }

        $insert = [
            'user_id'     => $this->member['id'],
            'title'       => $title,
            'content'     => $content,
            'agemin'      => $agemin,
            'agemax'      => $agemax,
            'heightmin'   => $heightmin,
            'heightmax'   => $heightmax,
            'province'    => $province,
            'city'        => $city,
            'education'   => $education,
            'images'      => $images,
            'expire_day'  => $expire_day,
            'create_time' => time(),
        ];

        if ($test) {
            $insert['state']       = 1;
            $insert['audit_time']  = $insert['create_time'];
            $insert['expire_time'] = $expire_day * 86400 + $insert['create_time'];
        }

        $res = Db::name('dating')->insert($insert);

        if ($res) {
            return $this->pass('发布成功');
        }
        return $this->miss('发布失败,请稍后重试');
    }

    /**
     * @return mixed
     */
    public function message() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $data = Db::name('dating_into')
            ->where(['touser_id' => $this->member['id']])
            ->order('is_read asc, id desc')
            ->page($page)
            ->limit($pagesize)
            ->select();
        $datings = Db::name('dating')->where(['id' => ['in', array_column($data, 'dating_id')]])->column('*', 'id');
        foreach ($data as &$value) {
            $value['userinfo']   = _user_cache($value['user_id']);
            $value['time']       = date('Y-m-d H:i', $value['time']);
            $value['datingInfo'] = $datings[$value['dating_id']];
            unset($value['datingInfo']['expire_day'], $value['datingInfo']['audit_time']);
            $value['datingInfo']['create_time'] = date('Y-m-d', $value['datingInfo']['create_time']);
            $value['datingInfo']['expire_time'] = date('Y-m-d', $value['datingInfo']['expire_time']);
        }
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function setRead() {
        $dm_ids = $this->params['dm_ids'] ?? '';
        $data   = Db::name('dating_into')
            ->where(['touser_id' => $this->member['id'], 'is_read' => 0, 'id' => ['in', $dm_ids]])
            ->update(['is_read' => 1]);

        return $this->pass('success');
    }

    /**
     * @return mixed
     */
    public function countunread() {
        $count = Db::name('dating_into')
            ->master()
            ->where(['touser_id' => $this->member['id'], 'is_read' => 0])
            ->count();

        return $this->pass(compact('count'));
    }

    public function close()
    {
        $id = $this->params['id'] ?? '';

        $timenow = time();
        $res = Db::name('dating')
            ->where(['id'=>$id,'user_id' => $this->member['id'],'expire_time'=>['>', $timenow]])
            ->update(['expire_time'=>$timenow,'state'=>-2,'reason'=>'用户自主关闭']);
        if (!$res) return $this->miss('操作失败');
        return $this->pass('已取消征婚');
    }

    public function info()
    {
        $id = $this->params['id'] ?? '14';

        $data = Db::name('dating')->find($id);
        if (!$data) return $this->miss('征婚信息不存在');
        $data['self'] = $data['user_id'] == $this->member['id'];
        if ($data['state'] != 1 && !$data['self']) return $this->miss('征婚信息不存在');

        $data['user'] = _user_cache($data['user_id'], 'id,name,head_portrait,sex,age,remote');

        if ($data['user']['remote'] == 10) {
            $images = explode(',',$data['images']);
            foreach ($images as &$imgv) {
                $imgv = changeUrl($imgv, 0);
            }
            $data['images'] = implode(',', $images);
            $data['user']['head_portrait'] = changeUrl($data['user']['head_portrait'], 0);
        }
        unset($data['user']['remote']);

        $data['create_time'] = date('Y-m-d H:i', $data['create_time']);
        $data['expire_time'] = date('Y-m-d H:i', $data['expire_time']);
        $data['audit_time'] = date('Y-m-d H:i', $data['audit_time']);
        if ($data['self']) {
            $data['into_list'] = Db::name('dating_into')
                ->alias('d')
                ->join('user u', 'd.user_id=u.id')
                ->where(['dating_id' => $id])
                ->field('head_portrait,name,user_id')
                ->limit(6)
                ->select();
        } else {
            $data['into_list'] = Db::name('dating_into')
                ->alias('d')
                ->join('user u', 'd.user_id=u.id')
                ->where(['dating_id' => $id])
                ->limit(6)
                ->column('head_portrait');
                $data['is_into'] = Db::name('dating_into')->master()->where(['user_id' => $this->member['id'], 'dating_id'=>$id])->count();
        }
        return $this->pass($data);
    }
}